package com.cheerscpl.loader;

import com.cheerscpl.annotation.EventHandler;
import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Executors;

/**
 * Created by chenpuliang on 2017/6/3.
 */
public class EventBusLoader implements ApplicationContextAware, InitializingBean{

    private static final Logger logger = LoggerFactory.getLogger(EventBusLoader.class);

    private Set<Object> handlers = new HashSet<>();

    private EventBus eventBus = new AsyncEventBus(Executors.newFixedThreadPool(
            Runtime.getRuntime().availableProcessors()+1));

    public EventBus getEventBus() {
        return eventBus;
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        Map<String, Object> map = ctx.getBeansWithAnnotation(EventHandler.class);
        if(null != map && map.size() != 0){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                handlers.add(entry.getValue());
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        for(Object handler : handlers){
            eventBus.register(handler);
            logger.debug("the handler: {} register success.", handler.getClass().getName());
        }
        logger.info("eventBusLoader registered success.");
    }
}
